package game.server;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;

import org.codehaus.jackson.JsonNode;

import domain.Agent;
import domain.HeadQuarter;
import domain.Map;
import domain.SedResponse;
import domain.Task;
import domain.Map.RoadBlock;
import play.libs.F;
import play.libs.WS;
import play.libs.WS.Response;
import play.mvc.Controller;

public class SedServiceHandler extends Controller implements
		F.Function<WS.Response, SedResponse> {

	@Override
	public SedResponse apply(Response response) throws Throwable {

		JsonNode respNode = response.asJson();

		SedResponse resp = new SedResponse();

		resp.status = respNode.get("status").asText();
		resp.statusMessage = respNode.get("statusMessage").asText();
		resp.turn = respNode.get("turn").asInt();

		resp.mapSize = respNode.get("mapSize").asInt();
		resp.money = respNode.get("money").asInt();
		
		resp.secondsLeft = respNode.get("money").asInt();
		
		// agents
		resp.agents = new ArrayList<Agent>();
		Iterator<JsonNode> agentIt = respNode.get("agents").getElements();
		
		while (agentIt.hasNext()) {
			JsonNode agentNode = (JsonNode) agentIt.next();
			Agent agent = new Agent(agentNode);
			resp.agents.add(agent);
		}
		
		// tasks
		resp.tasks = new ArrayList<Task>();
		Iterator<JsonNode> taskIter = respNode.get("tasks").getElements();
		while (taskIter.hasNext()) {
			JsonNode jsonNode = (JsonNode) taskIter.next();
			
			Task taks = new Task(jsonNode);
			resp.tasks.add(taks);
			
		}
		
		// headquartest
		resp.headQuarters = new ArrayList<HeadQuarter>();
		Iterator<JsonNode> headQIter = respNode.get("headQuarters").getElements();
		while (headQIter.hasNext()) {
			JsonNode jsonNode = (JsonNode) taskIter.next();
			
			HeadQuarter headQuarter = new HeadQuarter(jsonNode);
			resp.headQuarters.add(headQuarter);
			
		}
		
		// roadblocks
		resp.roadBlocks = new ArrayList<Map.RoadBlock>();
		Iterator<Entry<String, JsonNode>> rbfields = respNode.get("roadBlocks").getFields();
		while (rbfields.hasNext()) {
			
			java.util.Map.Entry<java.lang.String, org.codehaus.jackson.JsonNode> entry =
				(java.util.Map.Entry<java.lang.String, org.codehaus.jackson.JsonNode>) rbfields.next();
			
			RoadBlock roadBlock = new RoadBlock(entry);
			
			resp.roadBlocks.add(roadBlock);
			
		}
		
		
		return resp;
	}

}
